<template>
  <div class="host">
    <div class="date-head">
      <el-radio-group v-model="searchType" size="mini" @change="changeTime">
        <el-radio-button label="1">近一日</el-radio-button>
        <el-radio-button label="2">近一周</el-radio-button>
        <el-radio-button label="3">近一月</el-radio-button>
        <el-radio-button label="4">自定义</el-radio-button>
      </el-radio-group>
      <el-date-picker
        v-if="searchType == '4'"
        v-model="pickTime"
        type="daterange"
        size="small"
        clearable
        value-format="yyyy-MM-dd"
        placeholder="选择日期"
        @change="changeTime"
      />
    </div>
    <div class="data-list hk-flex">
      <div class="box">
        <div class="title">分析概览</div>
        <div class="content hk-flex">
          <div v-for="(item, index) in taskAnalysisDatas" :key="index" class="content-list hk-flex">
            <div>{{ item.name }}</div>
            <div class="c-bottom">
              <div>
                <span class="totalnum" @click="handleTaskAnalysis(item.type)" :title="item.count">{{ item.count>999?'999+':item.count }}</span>
                <span v-if="index==2||index==4||index==5">条</span>
                <span v-else>个</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="box marg-lr-20">
        <div class="title">实体信息</div>
        <div class="content hk-flex">
          <div
            v-for="(item, index) in entityInfoDatas"
            :key="index"
            class="hk-flex"
            @click="handleEntityInfo(item.name)"
          >
            <div style="margin-right: 20px">
              <img
                class="icon-img"
                :src="item.iconUrl || require('@/assets/images/sjjr_jrsjy_01.png')"
                alt
              >
            </div>
            <div class="content-info" style="flex: 1">
              <div style="font-size:18px">{{ item.name }}</div>
              <div style="display: flex;align-items:flex-end">
                <span
                  :class="[
                    'font-size-30',
                    index == 0 ? 'font-blue' : index == 2 ? 'font-orange' : index == 1 ? 'font-green' : 'font-pink',
                  ]"
                >{{ item.total>999?'999+':item.total }}</span>
                <span style="margin-left: 10px">{{ index == 0 ? '台' : '个' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="box">
        <div class="title">行为标签</div>
        <treeMapEchart ref="treeMapEchartRef" height="240px" @handleClick="handleClickTreeMap" />
      </div>
    </div>
    <div class="data-list hk-flex">
      <div class="box">
        <div class="title">任务分析方式</div>
        <div v-for="(item, index) in analyzeDatas" :key="index" class="column hk-flex">
          <span>{{ item.name }}</span>
          <el-progress
            style="flex: 1; margin-left: 20px;"
            :percentage="Math.round(item.count/item.totalNum*100)||0"
            :text-inside="true"
            :stroke-width="16"
            :color="customColors(index)"
          />
          <span style="display:inline-block;width:50px;text-align:right;overflow:hidden;text-overflow:ellipsis ;white-space: nowrap;">{{ item.count }}</span>
        </div>
        <div class="title" style="margin-top: 20px">任务状态</div>
        <taskStatusEchart ref="taskStatusRef" />
      </div>
      <div class="box" style="margin: 0 20px">
        <div class="title">
          任务执行详情
          <span
            class="font-blue font-size-14 font-pointer"
            @click="$router.push({ path:prefix+'/icp/rule', query: { name: 'icpHome' } })"
          >更多</span>
        </div>
        <HkTable
          ref="table"
          :loading="loading"
          :table-data="tableData"
          :table-columns="tableLabelList"
          :show-pag="false"
          :show-index="true"
          :table-height="80"
        >
          <template #status="scope">
            <span v-if="scope.row.status == '1'" class="font-green">启用</span>
            <span v-else class="font-red">停用</span>
          </template>
          <template #analyseType="scope">
            <dict-label :options="analyseTypeList" :value="scope.row.analyseType" />
          </template>
        </HkTable>
      </div>
      <div class="box">
        <div class="title">分析模型</div>
        <HkTable
          ref="table"
          :loading="loading"
          :table-height="80"
          :table-data="modelTableData"
          :table-columns="modelTableLabelList"
          :show-pag="false"
          :show-index="true"
        />
      </div>
    </div>
    <div class="data-list hk-flex">
      <div class="box">
        <div class="title">监管指标</div>
        <el-row v-if="pieData1.data.length > 0" :gutter="20" class="things">
          <el-col :span="8">
            <pieEchart :cdata="pieData1" height="340px" @handleClick="val=>handleClick(val,1)" />
          </el-col>
          <el-col :span="8">
            <pieEchart :cdata="pieData2" height="340px" @handleClick="val=>handleClick(val,2)" />
          </el-col>
          <el-col :span="8">
            <pieEchart :cdata="pieData3" height="340px" @handleClick="val=>handleClick(val,3)" />
          </el-col>
        </el-row>
      </div>
      <div class="box" style="margin-left: 20px">
        <div class="title">安全保密事件趋势</div>

        <lineEchart v-if="eventTrendsData.value.length" height="340px" :cdata="eventTrendsData" />
        <el-empty v-else description="暂无数据" />
      </div>
    </div>
  </div>
</template>

<script>
import DictLabel from '@/components/Common/dictLabel.vue'
import taskStatusEchart from './components/taskStatusEchart'
import pieEchart from './components/pieEchart'
import lineEchart from './components/lineEchart.vue'
import treeMapEchart from './components/treeMapEchart'
import HkTable from '@/components/Hk-Table/index'
import { getOverviewData, getTaskData, getMetricsEventData } from '@/api/icp/home.js'
import { ENTITY_TYPE } from '@/constants'

export default {
  components: { DictLabel, taskStatusEchart, HkTable, pieEchart, lineEchart, treeMapEchart },
  data() {
    return {
      prefix: window.prefix,
      searchType: '1',
      pickTime: undefined,
      starTime: '',
      endTime: '',
      loading: false,
      entityTypeList: ['host', 'person', 'app', 'account'],
      analyseTypeList: [
        {
          label: '触发分析',
          value: '1'
        },
        {
          label: '聚合分析',
          value: '2'
        },
        {
          label: '时序分析',
          value: '3'
        }
      ],
      // 分析概览
      taskAnalysisDatas: [
        {
          type: 'entityCount',
          name: '实体信息',
          count: 0
        },
        {
          type: 'behaviorCount',
          name: '行为标签',
          count: 0
        },
        {
          type: 'ruleCount',
          name: '分析任务',
          count: 0
        },
        {
          type: 'ruleModelCount',
          name: '分析模型',
          count: 0
        },
        {
          type: 'metricsCount',
          name: '监管指标',
          count: 0
        },
        {
          type: 'eventCount',
          name: '安全保密事件',
          count: 0
        }
      ],
      //   实体信息
      entityInfoDatas: [],
      // 任务分析方式
      analyzeDatas: [
        {
          type: 'batchCount',
          name: '聚合分析',
          count: 0
        },
        {
          type: 'streamCount',
          name: '触发分析',
          count: 0
        },
        {
          type: 'sequenceCount',
          name: '序列分析',
          count: 0
        }
      ],
      //  任务执行情况
      tableData: [],
      // 任务执行详情
      tableLabelList: [
        { label: '任务名称', param: 'name' },
        { label: '状态', param: 'status', type: 'slot', width: '60' },
        { label: '分析方式', param: 'analyseType', type: 'slot', width: '120' }
      ],
      // 分析模型数据
      modelTableData: [],
      modelTableLabelList: [
        { label: '模型名称', param: 'modelName' },
        { label: '命中次数', param: 'count', width: '80' },
        { label: '最后执行时间', param: 'latestLogTimeStr', width: '160' }
      ],
      pieData1: {
        title: '指标分类',
        legendShow: true,
        legendHeight: 80,
        color: ['#FF7675', '#FFA241', '#5FCA99', '#4B6EEF'],
        data: [
          { value: 0, name: '网络攻击' },
          { value: 0, name: '用户违规' },
          { value: 0, name: '运维异常' },
          { value: 0, name: '设备故障' }
        ]
      },
      pieData2: {
        title: '指标级别',
        legendShow: true,
        legendHeight: 80,
        color: ['#FF7675', '#FFA241', '#5FCA99', '#4B6EEF'],
        data: [
          { value: 0, name: '一般' },
          { value: 0, name: '较大' },
          { value: 0, name: '重大' },
          { value: 0, name: '特别重大' }
        ]
      },
      pieData3: {
        title: '监管对象分类',
        legendShow: true,
        legendHeight: 80,
        color: ['#FF7675', '#FFA241', '#5FCA99', '#4B6EEF'],
        data: [
          { value: 0, name: '终端' },
          { value: 0, name: '网络' },
          { value: 0, name: '人员' },
          { value: 0, name: '应用' }
        ]
      },
      //   安全保密事件趋势
      eventTrendsData: {
        color: '#3ABF81',
        legendName: ['安全保密事件'],
        xAxis: ['6:00', '7:00', '8:00', '9:00', '10:00', '11:00', '12:00'],
        value: [0, 0, 0, 0, 0, 0, 0]
      },
      treeMapData: {}
    }
  },
  mounted() {
    this.getOverview()
    this.getTask()
    this.getMetricsEvent()
  },
  methods: {
    /** 改变时间  */
    changeTime() {
      if (this.pickTime) {
        this.startTime = this.pickTime[0]
        this.endTime = this.pickTime[1]
      } else {
        this.startTime = ''
        this.endTime = ''
      }
      this.getMetricsEvent({ searchType: this.searchType, startTime: this.startTime, endTime: this.endTime })
    },
    /**  获取 分析概览、实体信息、行为标签的数据 */
    getOverview() {
      getOverviewData().then(res => {
        // 分析概览
        this.taskAnalysisDatas.forEach(i => {
          switch (i.type) {
            case 'entityCount':
              i.count = res.entityCount
              break
            case 'behaviorCount':
              i.count = res.behaviorCount
              break
            case 'ruleCount':
              i.count = res.ruleCount
              break
            case 'ruleModelCount':
              i.count = res.ruleModelCount
              break
            case 'metricsCount':
              i.count = res.metricsCount
              break
            case 'eventCount':
              i.count = res.eventCount
              break
            default:
              break
          }
        })
        //  实体信息
        this.entityInfoDatas = res.entityList.filter(o => this.entityTypeList.includes(o.entityId)).map((i) => {
          return {
            name: i.entityName,
            id: i.entityId,
            iconUrl: ENTITY_TYPE[i.entityId]?.iconUrl || undefined,
            total: i.total
          }
        })
        //   行为标签
        this.getTreeMapData(res.behaviorList)
      })
    },
    //  实体信息 - 更多
    handleMore() {},
    //  获取行为标签的数据
    getTreeMapData(data) {
      this.$nextTick(() => {
        this.changeDataStructure(data)
        this.treeMapData.data = data
        this.$refs.treeMapEchartRef.setOption(this.treeMapData)
      })
    },
    // 重构数据结构
    changeDataStructure(data) {
      if (data.length > 0) {
        data.forEach((item, index) => {
          if (item.fieldAlias) {
            item.name = item.fieldAlias
            delete item.fieldAlias
          }
          if (item.total) {
            item.value = item.total
            delete item.total
          }
          if (item.children) {
            this.changeDataStructure(item.children)
          }
        })
        return data
      }
    },

    /**
     * 获取 任务分析方式、任务执行详情、分析模型的数据
     * */
    getTask() {
      getTaskData().then(res => {
        //  任务分析方式
        this.analyzeDatas.forEach(item => {
          switch (item.type) {
            case 'batchCount':
              item.count = res.batchCount
              break
            case 'streamCount':
              item.count = res.streamCount
              break
            case 'sequenceCount':
              item.count = res.sequenceCount
              break
            default:
              break
          }
          item.totalNum = res.batchCount + res.streamCount + res.sequenceCount
        })
        this.$refs.taskStatusRef.getData({
          enableCount: res.enableCount,
          disableCount: res.disableCount
        })
        // 任务执行情况
        this.tableData = res.ruleList
        //  分析模型
        this.modelTableData = res.ruleModelList
      })
    },
    /**
     * 获取 监管指标、安全保密事件趋势
     * */
    getMetricsEvent(query) {
      const arr = ['一般', '较大', '重大', '特别重大']
      getMetricsEventData(query).then(res => {
        this.pieData1.data = res.categoryTags.sort((a, b) => a?.name?.length - b?.name?.length)
        this.pieData2.data = arr.map(item => {
          const it = res.levelTags.filter(i => i.name === item)[0]
          return it
        })
        this.pieData3.data = res.objectTags.sort((a, b) => a?.name?.length - b?.name?.length)
        this.eventTrendsData.xAxis = res.eventList.map(i => {
          return i.name
        })
        this.eventTrendsData.value = res.eventList.map(i => {
          return i.value
        })
      })
    },
    //  进度条-颜色设置
    customColors(index) {
      if (index === 0) {
        return '#FF3535'
      } else if (index === 1) {
        return '#FFC53D'
      } else if (index === 2) {
        return '#4B6EEF '
      }
    },
    //  进度条-进度
    getPercentage(item) {
      let sum = 0
      this.analyzeDatas.forEach(item => {
        sum += item.count
      })
      // return Number(((item.count / sum) * 100).toFixed(2))
      return item.count
    },
    //  format
    // format(percentage) {
    //   const p = percentage <= 0 ? 0 : percentage >= 100 ? 100 : percentage
    //   return p + '%'
    // },
    // 分析概览点击跳转事件
    handleTaskAnalysis(type) {
      let router = ''
      switch (type) {
        case 'entityCount':
          return
        // router = '/icp/data/entity'
        // break
        case 'behaviorCount':
          return
        // router = '/icp/data/behavior'
        // break
        case 'ruleCount':
          router = '/icp/rule'
          break
        case 'ruleModelCount':
          router = '/icp/model'
          break
        case 'metricsCount':
          router = '/icp/metrics'
          break
        case 'eventCount':
          router = '/dispose/incidentHandle'
          break
        default:
          break
      }
      this.$router.push({ path: window.prefix + router, query: { name: 'icpHome' }})
    },
    // 实体信息点击跳转
    handleEntityInfo(name) {
      // this.$router.push({ path: '/icp/data/entity', query: { name: name } })
    },
    // 行为标签点击跳转
    handleClickTreeMap(val) {
      // this.$router.push({ path: '/icp/data/behavior', query: { id: val.data.id } })
    },
    // 饼状图点击跳转
    handleClick(data, index) {
      const query = { name: 'icpHome' }
      switch (index) {
        case 1:
          query.event_category = data.data.code
          break
        case 2:
          query.event_level = data.data.code
          break
        case 3:
          query.monitor_object = data.data.code
          break
      }
      this.$router.push({ path: window.prefix + '/icp/metrics', query: query })
    }
  }
}
</script>

<style lang="scss" scoped>
#app.dark-theme .host {
  color: #fff;
}
::v-deep .el-progress-bar {
  width: 97%;
}
::v-deep .el-table {
  margin-top: 0 !important;
}
.tableCell {
  width: 100%;
  display: inline-block;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.host {
  padding: 20px;
  background: #f3f5fb;
  width: 100%;
  height: 100%;
  overflow: auto;

  .date-head {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    justify-content: flex-end;

    .el-date-editor {
      margin-left: 20px;
    }
  }

  .marg-lr-20 {
    margin: 0 20px;
  }

  .data-list {
    width: 100%;
    //flex-wrap:wrap;
    align-items: stretch;
    justify-content: space-between;

    &:nth-of-type(n + 2) {
      margin-top: 20px;
      .box {
        width: 34%;
      }
    }
  }

  .icon-img {
    width: 70px;
    height: 70px;
  }

  .font-size-30 {
    font-size: 30px;
  }

  .font-size-14 {
    font-size: 14px;
  }

  .font-pointer {
    cursor: pointer;
  }

  .font-blue {
    color: #4b6eef;
  }

  .font-orange {
    color: #fa8c16;
  }

  .font-red {
    color: #ff3535;
  }

  .font-green {
    color: #3abf81;
  }

  .font-pink {
    color: #ff5153;
  }

  .targetTable {
    height: 410px;
    padding-bottom: 0 !important;
  }
  .content-info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
  .box {
    flex: 1;
    background: white;
    padding: 20px;
    overflow: auto;
    display: flex;
    flex-direction: column;

    .column {
      padding: 10px;
    }

    .content {
      justify-content: space-between;
      flex-wrap: wrap;
      .hk-flex {
        align-items: stretch;
        .content-info {
          padding: 5px 0;
          .font-size-30 {
            line-height: 26px;
          }
        }
      }
      & > div {
        width: calc(50% - 10px);
        background: #f3f5fb;
        border-radius: 4px;
        &:nth-of-type(2),
        &:first-of-type {
          .totalnum {
            cursor: default;
          }
        }
        &:nth-of-type(n + 3) {
          margin-top: 20px;
        }

        padding: 20px;
        justify-content: space-between;

        .totalnum {
          margin-right: 5px;
          cursor: pointer;
          font-size: 24px;
          color: #4b6eef;
        }
      }
    }

    .title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 20px;
    }
  }
}
</style>
